import riceService from '@/services/rice-service';
import {
  PauseOutlined,
  PlayCircleOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  Descriptions,
  InputNumber,
  Progress,
  Space,
  message,
} from 'antd';
import React, { useEffect, useState } from 'react';
import './index.less';

// 定义完整的接口类型
interface TaskStatusResponse {
  status: 'idle' | 'running' | 'stopping';
  message: string;
  code: number;
  current_id?: number;
  start_id?: number;
  end_id?: number;
  progress?: number; // 直接使用数字类型的进度值
}

interface FormData {
  startId: number;
  endId: number;
}
interface RiceCrawlerProps {
  shouldPoll?: boolean; // 新增props
}

const RiceCrawlerPage: React.FC<RiceCrawlerProps> = ({ shouldPoll = true }) => {
  const [loading, setLoading] = useState(false);
  const [taskStatus, setTaskStatus] = useState<TaskStatusResponse>({
    status: 'idle',
    message: '没有正在运行的任务',
    code: 0,
  });
  const [formData, setFormData] = useState<FormData>({
    startId: 632380,
    endId: 632381,
  });

  // 获取任务状态
  const fetchStatus = async () => {
    try {
      const { data } = await riceService.rice_status();
      setTaskStatus(data);
    } catch (err) {
      message.error('获取状态失败');
    }
  };

  // 启动任务
  const startTask = async () => {
    if (formData.startId > formData.endId) {
      message.error('起始ID必须小于结束ID');
      return;
    }

    setLoading(true);
    try {
      await riceService.rice_run_get({
        start_id: formData.startId,
        end_id: formData.endId,
      });
      message.success('任务已启动');
      // 立即刷新状态
      await fetchStatus();
    } catch (err) {
      message.error('启动任务失败');
    } finally {
      setLoading(false);
    }
  };

  // 停止任务
  const stopTask = async () => {
    setLoading(true);
    try {
      await riceService.rice_stop();
      message.success('停止请求已发送');
      setTaskStatus((prev) => ({
        ...prev,
        status: 'stopping',
      }));
    } catch (err) {
      message.error('停止任务失败');
    } finally {
      setLoading(false);
    }
  };

  // 修改后的useEffect轮询逻辑
  useEffect(() => {
    let timer: NodeJS.Timeout;

    const startPolling = () => {
      fetchStatus(); // 立即获取一次
      timer = setInterval(fetchStatus, 3000);
    };

    if (shouldPoll) {
      startPolling();
    }

    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [shouldPoll]); // 依赖shouldPoll变化
  // 计算进度百分比
  const calculateProgress = (): number => {
    if (taskStatus.status !== 'running') return 0;

    // 直接使用API返回的progress值（可能为负数）
    if (taskStatus.progress !== undefined) {
      return taskStatus.progress;
    }

    // 备用计算方式（如果progress未提供）
    const start = taskStatus.start_id || formData.startId;
    const end = taskStatus.end_id || formData.endId;
    const current = taskStatus.current_id || start;

    if (start === end) return 0;
    return Math.round(((current - start) / (end - start)) * 100);
  };

  const getProgressStatus = () => {
    if (taskStatus.status !== 'running') return 'normal';
    if (taskStatus.progress === -50) return 'exception'; // 准备中显示异常状态
    if (taskStatus.progress === -75) return 'exception'; // 初始化中显示异常状态
    return 'active';
  };

  const formatProgressText = (percent: number) => {
    if (percent === -50) return '准备中';
    if (percent === -75) return '初始化中';
    return `${percent}%`;
  };

  const progressPercent = calculateProgress();

  return (
    <div className="rice-crawler-container">
      <div className="rice-crawler-header">
        <h2>水稻数据采集系统</h2>
        <p>自动抓取水稻品种数据信息</p>
      </div>

      <Card title="任务控制" className="rice-crawler-control-card">
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <Descriptions column={1}>
            <Descriptions.Item label="起始ID">
              <InputNumber
                min={600000}
                max={700000}
                value={formData.startId}
                onChange={(value) =>
                  setFormData({ ...formData, startId: value || 0 })
                }
              />
            </Descriptions.Item>
            <Descriptions.Item label="结束ID">
              <InputNumber
                min={600000}
                max={700000}
                value={formData.endId}
                onChange={(value) =>
                  setFormData({ ...formData, endId: value || 0 })
                }
              />
            </Descriptions.Item>
          </Descriptions>

          <Space>
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              onClick={startTask}
              loading={loading && taskStatus.status === 'idle'}
              disabled={taskStatus.status === 'running'}
            >
              启动任务
            </Button>
            <Button
              danger
              icon={<PauseOutlined />}
              onClick={stopTask}
              loading={loading && taskStatus.status !== 'idle'}
              disabled={taskStatus.status === 'idle'}
            >
              停止任务
            </Button>
            <Button icon={<SyncOutlined />} onClick={fetchStatus}>
              刷新状态
            </Button>
          </Space>
        </Space>
      </Card>
      <Card title="任务状态" className="rice-crawler-status-card">
        <div className="progress-container">
          <Progress
            percent={Math.abs(progressPercent)} // 显示绝对值
            status={getProgressStatus()}
            format={() => formatProgressText(progressPercent)}
          />
          <p>当前处理ID: {taskStatus.current_id || '-'}</p>
          <p>状态消息: {taskStatus.message}</p>
        </div>

        <Descriptions bordered>
          <Descriptions.Item label="任务状态" span={3}>
            <span className={`status-${taskStatus.status}`}>
              {taskStatus.message ||
                (taskStatus.status === 'idle'
                  ? '空闲'
                  : taskStatus.status === 'running'
                    ? '运行中'
                    : '停止中')}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="起始ID">
            {taskStatus.start_id || formData.startId}
          </Descriptions.Item>
          <Descriptions.Item label="结束ID">
            {taskStatus.end_id || formData.endId}
          </Descriptions.Item>
          <Descriptions.Item label="当前ID">
            {taskStatus.current_id || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="进度" span={2}>
            {formatProgressText(progressPercent)}
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </div>
  );
};

export default RiceCrawlerPage;
